package pres.wchen.oa.cor.shiro.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.crazycake.shiro.SerializeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pres.wchen.oa.cor.shiro.model.BaseModel;
import pres.wchen.oa.cor.shiro.model.SysPermission;
import pres.wchen.oa.cor.shiro.model.SysRole;
import pres.wchen.oa.cor.shiro.model.SysUser;
import pres.wchen.oa.cor.shiro.service.SysPermissionService;
import pres.wchen.oa.cor.shiro.service.SysRoleService;
import pres.wchen.oa.cor.shiro.service.SysUserService;

import java.util.*;

/**
 * @作者： wchen
 * @描述：
 * @创建时间： 2018/1/15 23:40
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class MyRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("------权限认证方法：MyShiroRealm.doGetAuthenticationInfo()------");
        Object objToken = SecurityUtils.getSubject().getPrincipal();
        System.out.println(objToken.getClass().getName());
        System.out.println(SysUser.class.getName());
        SysUser token = new SysUser();
        if(objToken instanceof SysUser) {
            token = (SysUser) objToken;

        }
        Long userId = token.getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();

        //根据用户ID查询角色（role），放入到Authorization里。
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        List<SysRole> sysRoleList = sysRoleService.list(map).getList();
        Set roleSet = new HashSet();
        for(SysRole sysRole : sysRoleList){
            roleSet.add(sysRole.getRoleName());
        }
        info.addRoles(roleSet);

        /*Map<String, Object> map = new HashMap<String, Object>();
        map.put("user_id", userId);
        List<SysRole> roleList = sysRoleService.selectByMap(map);
        Set<String> roleSet = new HashSet<String>();
        for(SysRole role : roleList){
            roleSet.add(role.getType());
        }*/
        //实际开发，当前登录用户的角色和权限信息是从数据库来获取的，我这里写死是为了方便测试
//        Set<String> roleSet = new HashSet<>();
//        roleSet.add("100002");
//        info.setRoles(roleSet);
        //根据用户ID查询权限（permission），放入到Authorization里。
    /*List<SysPermission> permissionList = sysPermissionService.selectByMap(map);
    Set<String> permissionSet = new HashSet<String>();
    for(SysPermission Permission : permissionList){
        permissionSet.add(Permission.getName());
    }*/
        Set permissionSet = new HashSet();
        List<SysPermission> permissionList = sysUserService.queryUserPermissions(userId);
        for(SysPermission sysPermission : permissionList){
            permissionSet.add(sysPermission.getPermissionName());
        }
        info.setStringPermissions(permissionSet);
        return info;
//        return null;
    }



    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     * @param authcToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        logger.info("-------身份认证方法：MyShiroRealm.doGetAuthenticationInfo()-------");

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        SysUser user = sysUserService.doLogin(token.getUsername());
        // 从数据库获取对应用户名密码的用户
//        List<SysUser> userList = sysUserService.selectByMap(map);
//        if(userList.size()!=0){
//            user = userList.get(0);
//        }
//        if (null == user) {
//            throw new AccountException("帐号或密码不正确！");
//        }else if(user.getStatus().equals("0")){
//            /**
//             * 如果用户的status为禁用。那么就抛出<code>DisabledAccountException</code>
//             */
//            throw new DisabledAccountException("帐号已经禁止登录！");
//        }else{
            //更新登录时间 last login time
//            user.setLastLoginTime(new Date());
//            sysUserService.updateById(user);
//        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }



}
